﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PubSubLite.Configuration;
using PubSubLite.Utils;

namespace PubSubLite.Messaging.MessageChannels
{
    /// <summary>
    /// Provides available message channels
    /// </summary>
    public class MessageChannelProvider : IMessageChannelProvider
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="configuration"></param>
        public MessageChannelProvider(IBusConfiguration configuration)
        {
            Require.Argument.IsNotNull(configuration, "configuration");
            _configuration = configuration;
            // Always add an InMemoryMessageChannel for internal routing
            _channels.Add(new InMemoryMessageChannel());
            // Tcp channels from config
            var configSection = _configuration.ConfigSection as PubSubLiteConfigurationSection;
            if (configSection != null)
            {
                for (var i = 0; i < configSection.TcpChannels.Count; i++)
                {
                    var tcpChannelConfig = configSection.TcpChannels[i];
                    _channels.Add(new TcpMessageChannel(configuration, tcpChannelConfig));
                }
            }
        }

        private List<IMessageChannel> _channels = new List<IMessageChannel>();
        private IBusConfiguration _configuration;

        IEnumerable<IMessageChannel> IMessageChannelProvider.Channels
        {
            get { return _channels; }
        }

        IMessageChannel IMessageChannelProvider.GetChannelByID(Guid guid)
        {
            return _channels.Find(x => x.ID == guid);
        }
    }
}
